/* 
 * File:   TSFile.h
 * Author: thunderliu
 *
 * Created on 2013年6月4日, 下午4:42
 */

#ifndef __TSFILE_H__
#define	__TSFILE_H__

#include "TSIo.h"
#include "TSWorker.h"
#include <sys/mman.h>
#include <stdint.h>
#include <stdio.h>


class CFileMapping
{  
public:  
    CFileMapping();
    
    bool Init(const CIo* pIo, bool bReadOnly);
    bool Init(const char* pFileName, bool bReadOnly);
    bool Close();
    
    operator const void*() const;
    operator void*();
    size_t GetSize() const;
    void* GetAddress();
    
protected:
    void* m_pAddr;
    size_t m_uLen;
};

class CStdFile
{
public:
    enum FILE_ORIGIN
    {
        kBegin = SEEK_SET,
        kCur = SEEK_CUR,
        kEnd = SEEK_END
    };
    
public:
    CStdFile();
    virtual ~CStdFile();
    
    virtual bool Open(const char* pFileName, const char* pMode);
    bool Eof();
    
    template <typename TYPE>
    size_t Write(const TYPE* pData, size_t uCount = 1);
    
    template <typename TYPE>
    size_t Read(TYPE* pData, size_t uCount = 1);
    
    void Seek(long lOffset, FILE_ORIGIN eOrigin);
    
    size_t Tell();
    
    void Flush();
    
    virtual void Close();
    
    bool IsOpened() const;
    
    FILE* GetHandler();
    
    operator FILE*();
    
protected:
    FILE* m_pFile;
};

#include "TSThread.h"

class CAsyncWriteFile : public CWorker
{
public:
    virtual bool OnWork(CBlock16* pBlock); // donot release pBlock in this call
    virtual bool OnEmpty();
    virtual bool OnStop();
    
public:
    CStdFile* m_pFile;
};


class CAsyncFile : public CStdFile
{
public:
    static const int CONST_MAX_BLOCK = 10000;
    
public:
    virtual ~CAsyncFile();
    
    virtual bool Open(const char* pFileName, const char* pMode);
    
    template <typename TYPE>
    size_t AsyncWrite(const TYPE* pData, size_t uCount = 1);
    
    virtual void Close();
    
protected:
    CAsyncWriteFile m_oAsyncWriteFile;
};



#include "TSFile.inl"

#endif	/* __TSFILE_H__ */

